/**
 *
 * 入职登记，员工信息维护，员工信息查询的左树组件
 *
 * props: {
 *      onSelect: function(pk) {}, (选中了某个节点的回调)
 *      pk_org: '',(组织信息id)
 *      treeType: 'orgRange|adminOrg|psnType'(管理范围|行政组织|人员类别)(默认是orgRange)
 *      asyncTree: 平台的异步树的方法,
 *      treeId: 给树的数据起个名字
 *      MultiInit: 多语言方法
 * }
 *
 */

import React, {Component} from 'react';

import './index.less';

import getTreeRoot from './functions/getTreeRoot';
import getChildTree from './functions/getChildTreeData';

// 请求过子树数据的节点id存放在这里
// 每次请求前检查此数组，来判断是否请求过，请求过的不再请求
const hasFetchNode = [];

const treeTypeMapFn = (() => {
    const data = {};
    // 如此保证多次调用treeTypeMapFn 函数 使用的都是同一个data
    return (language) => {
        data['orgRange'] = language['hi6007-000008'],/* 国际化处理： 管理范围*/
            data['adminOrg'] = language['hi6007-000009'],/* 国际化处理： 行政组织*/
            data['psnType'] = language['hi6007-000010']/* 国际化处理： 人员类别*/
        return data;
    }
})();

class LeftContent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            pk: {},
            language: {}
        };

        this.loadTreeData = this.loadTreeData.bind(this);
        this.getTreeRootData = this.getTreeRootData.bind(this);
        this.selectNode = this.selectNode.bind(this);
        this.disableCancelDept = this.disableCancelDept.bind(this);
        this.handleDisable = this.handleDisable.bind(this);
        this.getLanguage = this.getLanguage.bind(this);
    }

    // 解决在禁用某子元素的时候，也可以让其点击有高亮反映的问题
    handleDisable(e) {
        if (this.props.include_cancle_dept) {
            let currentNode = e.target;
            let parentLiNode = getParentLiNode(currentNode);
            let liClassName = parentLiNode.className;

            let liList = e.currentTarget.querySelectorAll('li');

            Array.prototype.map.call(liList, (li) => {
                li.className = li.className.replace('disabledSelected', '');
                let childA = li.querySelector('.u-tree-node-selected');
                if (childA) {
                    childA.className = childA.className.replace('u-tree-node-selected', '');
                }
            });

            if (liClassName.indexOf('u-tree-treenode-disabled') >= 0) {
                parentLiNode.className = liClassName + ' disabledSelected';
                let childA = parentLiNode.querySelector('.u-tree-node-selected');
                if (childA) {
                    childA.className = childA.className + ' u-tree-node-selected';
                }
                this.props.onCancelClick && this.props.onCancelClick();
            }
        }
    }

    componentDidMount() {
    }

    getLanguage() {
        return new Promise((resolve, reject) => {
            if (Object.keys(this.state.language).length > 0) {
                resolve(this.state.language);
            } else {
                this.props.MultiInit.getMultiLang({
                    moduleId: 'p6007',
                    domainName: 'hrhi',
                    callback: (json, status, inlt) => {
                        this.setState({
                            language: json
                        }, () => {
                            resolve(json);
                        });
                    }
                });
            }
        });
    }

    selectNode(pk) {
        this.props.onSelect(pk);
    }

    // 禁用已撤销部门
    disableCancelDept(data) {
        const {
            asyncTree,
            treeId
        } = this.props;

        data && data.map((item) => {
            if (item.nodeData && item.nodeData.nodeValue && item.nodeData.nodeValue.hrcanceled) {
                asyncTree.setAsyncNodeDisable(treeId, true, item.refpk);
            }
        });
    }

    loadTreeData(pk, treeNode) {

        // 此处是自定义的根节点，所以不请求
        if (pk === 'custom_root' || hasFetchNode.indexOf(pk) >= 0) {
            return;
        }
        hasFetchNode.push(pk);

        const {
            pk_org,
            asyncTree,
            treeId,
            treeType,
            include_cancle_dept = false
        } = this.props;

        getChildTree({
            include_cancle_dept: include_cancle_dept,
            pk_org: pk_org,
            tree_node_id: pk,
            node_type: 'ORG_NODE',
            treeType: treeType
        })
            .then((res) => {
                if (res.success) {
                    /*if (treeType === "orgRange" && res.data) {
                        res.data.forEach(item => {
                            item.beforeName = item.code + " ";
                        })
                    }*/
                    asyncTree.setTreeData(treeId, res.data, treeNode);
                    this.disableCancelDept(res.data);
                }
            });
    }

    componentWillReceiveProps(nextProps) {
        // 是否切换了组织
        if (nextProps.pk_org !== this.props.pk_org || nextProps.treeType !== this.props.treeType) {
            hasFetchNode.length = 0;
            this.props.asyncTree.closeNodeByPkAsync(this.props.treeId);
            this.getTreeRootData(nextProps.pk_org, nextProps.treeType);
        }
        // 是否切换了左树类型
        if (nextProps.pk_org && nextProps.treeType !== this.props.treeType) {
            hasFetchNode.length = 0;
            this.props.asyncTree.closeNodeByPkAsync(this.props.treeId);
            this.getTreeRootData(nextProps.pk_org, nextProps.treeType);
        }
        // 是否包含撤销部门
        if (nextProps.pk_org && nextProps.include_cancle_dept !== this.props.include_cancle_dept) {
            hasFetchNode.length = 0;
            this.props.asyncTree.closeNodeByPkAsync(this.props.treeId);
            this.getTreeRootData(nextProps.pk_org, nextProps.treeType);
        }
    }

    getTreeRootData(pk_org, treeType) {
        const {
            treeId,
            asyncTree
        } = this.props;


        this.getLanguage()
            .then(() => {
                const {
                    language
                } = this.state;

                getTreeRoot({
                    pk_org: pk_org,
                    node_type: 'ORG_NODE',
                    treeType: treeType
                })
                    .then((res) => {
                        /*if (treeType === "orgRange" && res.data) {
                            res.data.forEach(item => {
                                item.beforeName = item.code + " ";
                            })
                        }*/
                        let root = [{
                            children: res.data,
                            code: treeTypeMapFn(language)[treeType],
                            iconBox: {
                                addIcon: false,
                                delIcon: false,
                                editIcon: false
                            },
                            id: null,
                            isOrgStruSort: false,
                            innercode: null,
                            key: 'root',
                            name: treeTypeMapFn(language)[treeType],
                            nodeData: {
                                nodeValue: {}
                            },
                            pid: null,
                            refname: treeTypeMapFn(language)[treeType],
                            refpk: 'custom_root',
                            title: treeTypeMapFn(language)[treeType]
                        }];
                        asyncTree.setTreeData(treeId, root);
                    });
            })
    }

    render() {
        const {
            asyncTree,
            treeId,
            treeType
        } = this.props;

        return (
            <div
                onClick={this.handleDisable}
            >
                {asyncTree.createAsyncTree({
                    treeId: treeId,
                    loadTreeData: this.loadTreeData,
                    showLine: true,
                    onSelectEve: this.selectNode,
                    editType: false,
                    renderTreeTitle: (item) => {
                    return item.refcode && treeType === "orgRange" ? item.refcode + " " + item.refname : item.refname
                }
                })}
            </div>
        );
    }
}

function getParentLiNode(dom) {
    if (dom.tagName && dom.tagName.toLowerCase() === 'li') {
        return dom;
    } else if (dom.parentNode) {
        return getParentLiNode(dom.parentNode);
    }
}

export default LeftContent;
